package backend.passedsystem.rsa.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ras/")

public class InfoController {
    final int p = 7;
    final int q = 11;
    final int e = 13;
    final int n = p * q;
    final int fn = (p-1)*(q-1);

    final int d = getd();

    public int getd()
    {
        for(int i = 1; i <= fn; i ++)
        {
            if((i * e) % fn == 1)
            {
                return i;
            }
        }
        return 0;
    }
    public int qmi(int m, int a, int mod)
    {
        int res = 1;
        while(a > 0)
        {
            if(a % 2 != 0)
            {
                res = (res * m) % mod;
            }
            m = (m * m) % mod;
            a /= 2;
        }
        return res % mod;
    }
    public StringBuffer getRas(String src)
    {
        StringBuffer res = new StringBuffer();
        for(int i = 0; i < src.length(); i ++)
        {
           int m = src.charAt(i) - '0';
           int b = qmi(m, e, n);
           String tem;
            if(b<10)
               tem = "0" + b;
           else
               tem = "" + b;
            res.append(tem);
        }
        return res;
    }
    public StringBuffer getreRas(String src)
    {
        int ans = (e*d)%fn;
        StringBuffer res1 = new StringBuffer();
        int tem = 0;
        for(int i = 0; i < src.length(); i ++)
        {
            int m = src.charAt(i) - '0';
            tem = tem * 10 + m;
            if((i+1) % 2 == 0)
            {
                int b = qmi(tem, d, n);
                res1.append(b);
                tem = 0;
            }
        }
        return res1;
    }
    @RequestMapping("passed/")
    public Map<String, String> getInfo()
    {
        Map<String, String> info = new HashMap<>();
        info.put("name", "RSA");
        info.put("rating", "RSA的安全性基于数论中大素数分解的困难性,首先选取两个保密的大素数p和q，计算n=p*q" +
                ",n的欧拉函数值就等于(p-1)*(q-1),选一整数e，满足e>1并且e<n的欧拉函数值且e和n的欧拉函数值互质" +
                "，计算d，满足d*e在模n的欧拉函数值的前提下等于1，即d是e在模n的欧拉函数值下的乘法逆元，因e与n的欧拉函数值互质，由模运算可知，它的乘法逆元一定存在" +
                "最后以{e, n}为公钥，{d, n}为私钥." );
        return info;
    }
    @RequestMapping("encry/")
    public void ajax(String name, HttpServletResponse response, HttpServletRequest request) throws IOException
    {
        StringBuffer src = getRas(name);
        response.getWriter().println(src);
    }
    @RequestMapping("reencry/")
    public void ajax1(String name, HttpServletResponse response, HttpServletRequest request) throws IOException
    {
        StringBuffer src = getreRas(name);
        response.getWriter().println(src);

    }
}
